package com.company.class8;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.JSONPath;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @Classname JsonPractice
 * @Description 类型说明
 * @Date 2022/5/2 18:26
 * @Created by zbw
 */

public class JsonPractice {
    public static void main(String[] args) {
        String ipResult = "jQuery110203029978798640218_1651483301471({\"Srcid\":\"5809\",\"ResultCode\":\"0\",\"status\":\"0\",\"QueryID\":\"2492844955\",\"Result\":[{\"DisplayData\":{\"strategy\":{\"tempName\":\"ip\",\"precharge\":\"0\",\"ctplOrPhp\":\"1\"},\"resultData\":{\"tplData\":{\"srcid\":\"5809\",\"resourceid\":\"5809\",\"OriginQuery\":\"3.3.3.3\",\"origipquery\":\"3.3.3.3\",\"query\":\"3.3.3.3\",\"origip\":\"3.3.3.3\",\"location\":\"\\u7f8e\\u56fd \\u4e9a\\u9a6c\\u900a\\u4e91\",\"userip\":\"\",\"showlamp\":\"1\",\"tplt\":\"ip\",\"titlecont\":\"IP\\u5730\\u5740\\u67e5\\u8be2\",\"realurl\":\"http:\\/\\/www.ip138.com\\/\",\"showLikeShare\":\"1\",\"shareImage\":\"1\",\"data_source\":\"AE\"},\"extData\":{\"tplt\":\"ip\",\"resourceid\":\"5809\",\"OriginQuery\":\"3.3.3.3\"}}},\"ResultURL\":\"http:\\/\\/www.ip138.com\\/\",\"Weight\":\"2\",\"Sort\":\"1\",\"SrcID\":\"5809\",\"ClickNeed\":\"0\",\"SubResult\":[],\"SubResNum\":\"0\",\"ar_passthrough\":[],\"RecoverCacheTime\":\"0\"}],\"data\":[{\"srcid\":\"5809\",\"resourceid\":\"5809\",\"OriginQuery\":\"3.3.3.3\",\"origipquery\":\"3.3.3.3\",\"query\":\"3.3.3.3\",\"origip\":\"3.3.3.3\",\"location\":\"\\u7f8e\\u56fd \\u4e9a\\u9a6c\\u900a\\u4e91\",\"userip\":\"\",\"showlamp\":\"1\",\"tplt\":\"ip\",\"titlecont\":\"IP\\u5730\\u5740\\u67e5\\u8be2\",\"realurl\":\"http:\\/\\/www.ip138.com\\/\",\"showLikeShare\":\"1\",\"shareImage\":\"1\"}],\"ResultNum\":\"1\"})";
        String regex1 = "\\{.*\\}";
        String regex2 = "\\((.*?)\\)";

        Pattern p1 = Pattern.compile(regex1);
        Pattern p2 = Pattern.compile(regex2);
        Matcher m1 = p1.matcher(ipResult);
        Matcher m2 = p2.matcher(ipResult);


        if(m1.find()){
            System.out.println(m1.group(0));
        }
        if(m2.find()){
            System.out.println(m2.group(0));
        }

        //不是个规范的json字符串，得先进行处理
        JSONObject jsonObject = JSON.parseObject(m1.group(0));
        System.out.println(jsonObject);
        //需求：获取OriginQuery的值
        //先获取json数组data
        JSONArray data = jsonObject.getJSONArray("data");
        System.out.println(data);
        //通过下标来获取数组中的值
        //get得到的是Object类型，强转为JsonObject
        JSONObject datajson = (JSONObject) data.get(0);
        System.out.println(datajson.getString("OriginQuery"));
        //JsonPath语言进行获取
        String jsonPath = "$.data[0].OriginQuery";
        Object read = JSONPath.read(m1.group(0), jsonPath).toString();
        System.out.println(read);


    }
}
